package i003.me.letterstudy;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RangeActivity extends AppCompatActivity
{
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_range);
        ButterKnife.bind(this);
        init();
    }

    private void init()
    {
        recyclerView.setItemAnimator(null);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(5, StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setAdapter(new LetterAdapter());
    }

    private class LetterAdapter extends BaseQuickAdapter<Character, BaseViewHolder>
    {
        private Character firstLetter;

        private LetterAdapter()
        {
            super(R.layout.letter_item);
            List<Character> data = new ArrayList<>();

            for(char ch = 'A'; ch <= 'Z'; ch++)
            {
                data.add(ch);
            }

            setNewData(data);
        }

        @Override
        protected void convert(BaseViewHolder holder, final Character item)
        {
            CheckBox checkBox = (CheckBox)holder.itemView;
            checkBox.setText(String.valueOf(item));
            checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
            {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    if(isChecked)
                    {
                        if(firstLetter == null)
                        {
                            firstLetter = item;
                        }
                        else
                        {
                            if(firstLetter.compareTo(item) < 0)
                            {
                                MainActivity.start(RangeActivity.this, firstLetter, item);
                            }
                            else
                            {
                                MainActivity.start(RangeActivity.this, item, firstLetter);
                            }

                            finish();
                        }
                    }
                    else
                    {
                        firstLetter = null;
                    }
                }
            });
        }
    }
}